﻿// Apache-2.0 License
// Copyright (c) 2021-2022 SuperJeff
// 微信:15906588664  QQ:1024489

using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Service.SRM.Dto;
using Admin.NET.Application.Const;
using Admin.NET.Core;
using Admin.NET.Core.Service;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Masuit.Tools;
using Microsoft.AspNetCore.Mvc;
using Nest;
using NPOI.SS.Formula.Functions;
using NPOI.SS.Util;
using SjEntityClass;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinUserInfoBatchGetRequest.Types;

namespace Admin.Net.InformationPlatform.Service.SRM
{
    /// <summary>
    /// SRM管理
    /// </summary>
    [ApiDescriptionSettings(groups: "SRM", Name = "报价管理", Tag = "报价管理", Order = 200)]

    public class SrmQuotationService : IDynamicApiController, ITransient
    {
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _Dilon;

        /// <summary>
        /// 用户信息
        /// </summary>
        TokenUser _User;

        /// <summary>
        /// srm报价管理模块
        /// </summary>
        /// <param name="db"></param>
        public SrmQuotationService(ISqlSugarClient db)
        {
            this.db = db;
            this._T100Db = this.db.AsTenant().GetConnection(T100Const.ConfigId);
            this._SjDb = this.db.AsTenant().GetConnection(SJDB.ConfigId);
            this._Dilon = this.db.AsTenant().GetConnection(Dilon.ConfigId);
            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db,_Dilon);


        }
        /// <summary>
        /// 获取报价未读数量(供应商)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/GetQuotationCount")]
        public async Task<int> GetQuotationCount()
        {
            if (_User.OrgId == "13901610784837")//供应商
            {
                string userid = '%' + _User.UserId + '%';
                var prolist = _SjDb.Ado.SqlQuery<string>($@"
                SELECT
	                count(*) count
                FROM
	                SJADMIN.SRMCG_LIST l
left join SJADMIN.SRMCG c on c.SRMCGID =l.SRMCG_ID 
left join SJADMIN.SRMBJ b on b.SRMCG_LISTID=l.SRMCG_LISTID and b.SRMGYSID='{_User.UserId}'
where l.SRMXJGYS like'{userid}' and  l.SRMISDELETE = 0 and (b.srmzt=0 or b.srmzt is null)
                ");
                return Convert.ToInt32(prolist[0]);
            }
            else
            {
                var prolist = _SjDb.Ado.SqlQuery<string>($@"
                SELECT
	                count(*) count
                FROM
	                SJADMIN.SRMBJ b
left join SJADMIN.SRMCG_LIST l on b.SRMCG_LISTID = l.SRMCG_LISTID
left join SJADMIN.SRMCG c on l.SRMCG_ID = c.SRMCGID
where c.SRMCGRID = '{_User.UserId}' and b.SRMISDELETE = 0 and b.SRMZT=1
                ");

                return Convert.ToInt32(prolist[0]);
            }


        }

        /// <summary>
        /// 根据采购需求获取所有报价信息
        /// </summary>
        /// <param name="SRMCGID"></param>
        /// <returns></returns>
        [HttpPost("/SRM/GetQuotationByCGData")]
        public async Task<List<SrmQuotationOutput>> GetQuotationByCGData(string SRMCGID)
        {
            var output = await _SjDb.Queryable<SRMBJ>().AS("SJADMIN.SRMBJ")
             .LeftJoin<SRMCG_LIST>((b, l) => (b.SRMCG_LISTID == l.SRMCG_LISTID))
             .LeftJoin<SRMCG>((b, l, c) => (l.SRMCG_ID == c.SRMCGID))
               .Where((b, l, c) => l.SRMCG_LISTID == SRMCGID)//根据采购id获取报价信息
             .Where((b, l, c) => (b.SRMISDELETE == 0))
             .OrderBy((b, l, c) => b.SRMBJTIME) //采购单日期排序
             .Select((b, l, c) => new SrmQuotationOutput
             {
                 SRMCG_ID = b.SRMCG_LISTID,
                 SRMPM = l.SRMPM,
                 SRMPH = l.SRMPH,
                 SRMGG = l.SRMGG,
                 SRMXHMC = l.SRMXHMC,
                 SRMXJGYS = l.SRMXJGYS,
                 SRMFJ = l.SRMFJ,
                 SRMBJID = b.SRMBJID,
                 SRMGYSID = b.SRMGYSID,
                 SRMBJTIME = b.SRMBJTIME,
                 SRMCG_LISTID = l.SRMCG_LISTID,
                 SRMBMCL = b.SRMBMCL,
                 SRMYLMC = b.SRMYLMC,
                 SRMYLJ = Convert.ToDouble(b.SRMYLJ),
                 SRMMZ = Convert.ToDouble(b.SRMMZ),
                 SRMJZ = Convert.ToDouble(b.SRMJZ),
                 SRMHLJ = Convert.ToDouble(b.SRMHLJ),
                 SRMHLF = Convert.ToDouble(b.SRMHLF),
                 SRMCLF = Convert.ToDouble(b.SRMCLF),
                 SRMBMCLF = Convert.ToDouble(b.SRMBMCLF),
                 SRMJGF = Convert.ToDouble(b.SRMJGF),
                 SRMDLBZ = b.SRMDLBZ,
                 SRMLY = b.SRMLY,
                 SRMBF = b.SRMBF,
                 SRMCLZB = Convert.ToDouble(b.SRMCLZB),
                 SRMSL = Convert.ToDouble(b.SRMSL),
                 SRM13SZJ = Convert.ToDouble(b.SRM13SZJ),
                 SRMLRBFB = Convert.ToDouble(b.SRMLRBFB),
                 SRMBJFJ = b.SRMBJFJ,
                 SRMZT = b.SRMZT,
                 SRMTHYY = b.SRMTHYY,
                 SRMBZ = b.SRMBZ,

                 SRMCREATE = b.SRMCREATE,
                 SRMISDELETE = b.SRMISDELETE,
                 SRMBJYXQ = l.SRMCREATE.ToDateTime().AddDays(l.SRMXJYXQ).AddHours(l.SRMXJYXQH),
                 ISGYS = "0",


             }).ToListAsync();
            return output;
        }

        /// <summary>
        /// 获取报价清单-分页
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/GetQuotationPagedList")]
        public async Task<SqlSugarPagedList<SrmQuotationOutput>> GetQuotationPagedList(SrmQuotationInput input)
        {
            //if (_User.OrgId == "344335052067141")//供应商
            if (_User.OrgId == "13901610784837")//供应商
            {
                var output = await _SjDb.Queryable<SRMCG_LIST>().AS("SJADMIN.SRMCG_LIST")
              .LeftJoin<SRMCG>((l, c) => (l.SRMCG_ID == c.SRMCGID))
              .LeftJoin<SRMBJ>((l, c, b) => (b.SRMCG_LISTID == l.SRMCG_LISTID && b.SRMGYSID == _User.UserId))
              .Where(l => l.SRMXJGYS.Contains(_User.UserId))//询价供应商包含当前登录供应商

              .Where(l => (l.SRMISDELETE == 0))
              //.Where((l,c,b) => b.SRMISDELETE == 0)
              .WhereIF(input.EndDate != null, (l, c, b) => ((b.SRMBJTIME <= input.EndDate) || b.SRMBJTIME == null)) //结束日期
              .WhereIF(input.StartDate != null, (l, c, b) => (b.SRMBJTIME >= input.StartDate) || b.SRMBJTIME == null) //开始日期
              .WhereIF(!string.IsNullOrEmpty(input.ProductNo), (l) => (l.SRMPM.Contains(input.ProductNo))) //品号
              .WhereIF(!string.IsNullOrEmpty(input.ProductName), (l) => (l.SRMPH.Contains(input.ProductName))) //品名
              .WhereIF(!string.IsNullOrEmpty(input.ProductSpecifications), (l) => (l.SRMGG.Contains(input.ProductSpecifications))) //规格

              .OrderBy((l, c, b) => l.SRMCREATE.ToDateTime().AddDays(l.SRMXJYXQ).AddHours(l.SRMXJYXQH)) //采购单日期排序

              .Select((l, c, b) => new SrmQuotationOutput
              {
                  SRMPM = l.SRMPM,
                  SRMPH = l.SRMPH,
                  SRMGG = l.SRMGG,
                  SRMXHMC = l.SRMXHMC,
                  SRMXJGYS = l.SRMXJGYS,
                  SRMCGZT = l.SRMZT,//采购状态
                  SRMFJ = l.SRMFJ,
                  SRMBJID = b.SRMBJID,
                  SRMGYSID = b.SRMGYSID,
                  SRMBJTIME = b.SRMBJTIME,
                  SRMCG_LISTID = l.SRMCG_LISTID,
                  SRMBMCL = b.SRMBMCL,
                  SRMYLMC = b.SRMYLMC,
                  SRMYLJ = Convert.ToDouble(b.SRMYLJ),
                  SRMMZ = Convert.ToDouble(b.SRMMZ),
                  SRMJZ = Convert.ToDouble(b.SRMJZ),
                  SRMHLJ = Convert.ToDouble(b.SRMHLJ),
                  SRMHLF = Convert.ToDouble(b.SRMHLF),
                  SRMCLF = Convert.ToDouble(b.SRMCLF),
                  SRMBMCLF = Convert.ToDouble(b.SRMBMCLF),
                  SRMJGF = Convert.ToDouble(b.SRMJGF),
                  SRMDLBZ = b.SRMDLBZ,
                  SRMLY = b.SRMLY,
                  SRMBF = b.SRMBF,
                  SRMCLZB = Convert.ToDouble(b.SRMCLZB),
                  SRMSL = Convert.ToDouble(b.SRMSL),
                  SRM13SZJ = Convert.ToDouble(b.SRM13SZJ),
                  SRMLRBFB = Convert.ToDouble(b.SRMLRBFB),
                  SRMBJFJ = b.SRMBJFJ,
                  SRMZT = b.SRMZT,
                  SRMTHYY = b.SRMTHYY,
                  SRMBZ = b.SRMBZ,

                  SRMCREATE = b.SRMCREATE,
                  SRMBJYXQ = l.SRMCREATE.ToDateTime().AddDays(l.SRMXJYXQ).AddHours(l.SRMXJYXQH),
                  SRMISDELETE = b.SRMISDELETE,
                  ISGYS = "1",
              })
              .ToPagedListAsync(input.Page, input.PageSize);
                return output;
            }
            else
            {
                var output = await _SjDb.Queryable<SRMBJ>().AS("SJADMIN.SRMBJ")
              .LeftJoin<SRMCG_LIST>((b, l) => (b.SRMCG_LISTID == l.SRMCG_LISTID))
              .LeftJoin<SRMCG>((b, l, c) => (l.SRMCG_ID == c.SRMCGID))
                .Where((b, l, c) => c.SRMCGRID == _User.UserId)//采购员为当前登录人
              .Where((b, l, c) => (b.SRMISDELETE == 0))
              //.Where((l,c,b) => b.SRMISDELETE == 0)
              .WhereIF(input.EndDate != null, (b, l, c) => ((b.SRMBJTIME <= input.EndDate) || b.SRMBJTIME == null)) //结束日期
              .WhereIF(input.StartDate != null, (b, l, c) => (b.SRMBJTIME >= input.StartDate) || b.SRMBJTIME == null) //开始日期
              .WhereIF(!string.IsNullOrEmpty(input.ProductNo), (b, l) => (l.SRMPM.Contains(input.ProductNo))) //品号
              .WhereIF(!string.IsNullOrEmpty(input.ProductName), (b, l) => (l.SRMPH.Contains(input.ProductName))) //品名
              .WhereIF(!string.IsNullOrEmpty(input.ProductSpecifications), (b, l) => (l.SRMGG.Contains(input.ProductSpecifications))) //规格

              .OrderBy((b, l, c) => b.SRMBJTIME) //采购单日期排序

              .Select((b, l, c) => new SrmQuotationOutput
              {
                  SRMPM = l.SRMPM,
                  SRMPH = l.SRMPH,
                  SRMGG = l.SRMGG,
                  SRMXHMC = l.SRMXHMC,
                  SRMXJGYS = l.SRMXJGYS,
                  SRMFJ = l.SRMFJ,
                  SRMBJID = b.SRMBJID,
                  SRMGYSID = b.SRMGYSID,
                  SRMBJTIME = b.SRMBJTIME,
                  SRMCG_LISTID = l.SRMCG_LISTID,
                  SRMBMCL = b.SRMBMCL,
                  SRMYLMC = b.SRMYLMC,
                  SRMYLJ = Convert.ToDouble(b.SRMYLJ),
                  SRMMZ = Convert.ToDouble(b.SRMMZ),
                  SRMJZ = Convert.ToDouble(b.SRMJZ),
                  SRMHLJ = Convert.ToDouble(b.SRMHLJ),
                  SRMHLF = Convert.ToDouble(b.SRMHLF),
                  SRMCLF = Convert.ToDouble(b.SRMCLF),
                  SRMBMCLF = Convert.ToDouble(b.SRMBMCLF),
                  SRMJGF = Convert.ToDouble(b.SRMJGF),
                  SRMDLBZ = b.SRMDLBZ,
                  SRMLY = b.SRMLY,
                  SRMBF = b.SRMBF,
                  SRMCLZB = Convert.ToDouble(b.SRMCLZB),
                  SRMSL = Convert.ToDouble(b.SRMSL),
                  SRM13SZJ = Convert.ToDouble(b.SRM13SZJ),
                  SRMLRBFB = Convert.ToDouble(b.SRMLRBFB),
                  SRMBJFJ = b.SRMBJFJ,
                  SRMZT = b.SRMZT,
                  SRMTHYY = b.SRMTHYY,
                  SRMBZ = b.SRMBZ,

                  SRMCREATE = b.SRMCREATE,
                  SRMISDELETE = b.SRMISDELETE,
                  SRMBJYXQ = l.SRMCREATE.ToDateTime().AddDays(l.SRMXJYXQ).AddHours(l.SRMXJYXQH),
                  ISGYS = "0",


              })
              .ToPagedListAsync(input.Page, input.PageSize);
                return output;
            }
        }
        /// <summary>
        /// 报价详情更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/UpdateQuotation")]
        public async Task<string> UpdateQuotation(SrmQuotationOutput input)
        {
            if ((new string[] { "0", "1", "2" }).Contains(input.SRMZT))
            {
                string fj = "";
                if (!string.IsNullOrEmpty(input.SRMBJFJ))
                {
                    fj = input.SRMBJFJ.TrimEnd(',');
                }
                //判断单据存在
                int cnt = await _SjDb.Queryable<SRMBJ>()
                    .Where(a => a.SRMBJID == input.SRMBJID)
                    .Select(a => a.SRMBJID)
                    .CountAsync();
                if (cnt == 0)
                {
                    var detailslist = new SRMBJ
                    {

                        SRMBJID = Guid.NewGuid().ToString("N"),
                        SRMGYSID = _User.UserId,
                        SRMBJTIME = DateTime.Now,
                        SRMCG_LISTID = input.SRMCG_LISTID,
                        SRMBMCL = input.SRMBMCL,
                        SRMYLMC = input.SRMYLMC,
                        SRMYLJ = input.SRMYLJ,
                        SRMMZ = input.SRMMZ,
                        SRMJZ = input.SRMJZ,
                        SRMHLJ = input.SRMHLJ,
                        SRMHLF = input.SRMHLF,
                        SRMCLF = input.SRMCLF,
                        SRMBMCLF = input.SRMBMCLF,
                        SRMJGF = input.SRMJGF,
                        SRMDLBZ = input.SRMDLBZ,
                        SRMLY = input.SRMLY,
                        SRMBF = input.SRMBF,
                        SRMCLZB = input.SRMCLZB,
                        SRMSL = input.SRMSL,
                        SRM13SZJ = input.SRM13SZJ,
                        SRMLRBFB = input.SRMLRBFB,
                        SRMBJFJ = fj,
                        SRMBZ = input.SRMBZ,
                        SRMTHYY = input.SRMTHYY,
                        SRMZT = input.SRMZT,

                        SRMCREATE = DateTime.Now,
                        SRMISDELETE = 0
                    };
                    #region 插入事务
                    try
                    {
                        //开启事务
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Insertable<SRMBJ>(detailslist).ExecuteCommandAsync();

                        if (count == 0)
                        {
                            throw Oops.Oh($"新建任务失败！");
                        }
                        //提交事务
                        _SjDb.Ado.CommitTran();
                        return "插入成功";
                    }
                    catch (Exception e)
                    {
                        //回滚事务
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                    #endregion
                }
                else
                {

                    //提交
                    try
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<SRMBJ>()
                            .SetColumns(a => a.SRMBJID == input.SRMBJID)

                        .SetColumns(a => a.SRMBJTIME == DateTime.Now)
                        .SetColumns(a => a.SRMCG_LISTID == input.SRMCG_LISTID)
                        .SetColumns(a => a.SRMBMCL == input.SRMBMCL)
                        .SetColumns(a => a.SRMYLMC == input.SRMYLMC)
                        .SetColumns(a => a.SRMYLJ == input.SRMYLJ)
                        .SetColumns(a => a.SRMMZ == input.SRMMZ)
                        .SetColumns(a => a.SRMJZ == input.SRMJZ)
                        .SetColumns(a => a.SRMHLJ == input.SRMHLJ)
                        .SetColumns(a => a.SRMHLF == input.SRMHLF)
                        .SetColumns(a => a.SRMCLF == input.SRMCLF)
                        .SetColumns(a => a.SRMBMCLF == input.SRMBMCLF)
                        .SetColumns(a => a.SRMJGF == input.SRMJGF)
                        .SetColumns(a => a.SRMDLBZ == input.SRMDLBZ)
                        .SetColumns(a => a.SRMLY == input.SRMLY)
                        .SetColumns(a => a.SRMBF == input.SRMBF)
                        .SetColumns(a => a.SRMCLZB == input.SRMCLZB)
                        .SetColumns(a => a.SRMSL == input.SRMSL)
                        .SetColumns(a => a.SRM13SZJ == input.SRM13SZJ)
                        .SetColumns(a => a.SRMLRBFB == input.SRMLRBFB)
                        .SetColumns(a => a.SRMBJFJ == fj)
                        .SetColumns(a => a.SRMBZ == input.SRMBZ)
                        .SetColumns(a => a.SRMTHYY == input.SRMTHYY)
                        .SetColumns(a => a.SRMZT == input.SRMZT)
                        .Where(a => a.SRMBJID == input.SRMBJID)
                        .ExecuteCommandAsync();

                        if (count != 1)
                        {
                            throw Oops.Oh("修改失败！");
                        }


                        _SjDb.Ado.CommitTran();
                        return "修改成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }

            }
            else
            {
                throw Oops.Oh("状态码提交异常，驳回！");
            }

        }
        /// <summary>
        /// 报价状态更改
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/SRM/SubmitQuotation")]
        public async Task<string> SubmitQuotation(SubmitQuotationZT input)
        {

            if ((new string[] { "1", "2", "3", "4", "5" }).Contains(input.SRMZT))
            {
                //判断单据存在
                int cnt = await _SjDb.Queryable<SRMBJ>()
                    .Where(a => a.SRMBJID == input.SRMBJID)
                .Select(a => a.SRMBJID)
                    .CountAsync();

                var list = await _SjDb.Queryable<SRMBJ>()
                    .Where(a => a.SRMBJID == input.SRMBJID)
                    .Select<SRMBJ>()
                    .ToListAsync();

                if (cnt == 0)
                {
                    throw Oops.Oh("任务不存在，驳回！");
                }
                else
                {
                    //提交
                    try
                    {
                        _SjDb.Ado.BeginTran();
                        int count = await _SjDb.Updateable<SRMBJ>()
                            .SetColumns(a => a.SRMZT == input.SRMZT)
                            .Where(a => a.SRMBJID == input.SRMBJID)
                            .ExecuteCommandAsync();
                        if (input.SRMZT == "4")//其余报价单修改为报价失败,询价需求完成
                        {
                            count += await _SjDb.Updateable<SRMBJ>()
                             .SetColumns(a => a.SRMZT == "5")
                             .Where(a => a.SRMCG_LISTID == list[0].SRMCG_LISTID && a.SRMBJID != input.SRMBJID)
                             .ExecuteCommandAsync();
                            count += await _SjDb.Updateable<SRMCG_LIST>()
                             .SetColumns(a => a.SRMZT == 1)
                             .Where(a => a.SRMCG_LISTID == list[0].SRMCG_LISTID)
                             .ExecuteCommandAsync();
                        }


                        if (count < 0)
                        {
                            throw Oops.Oh("修改状态失败！");
                        }


                        _SjDb.Ado.CommitTran();
                        return "提交成功！";
                    }
                    catch (Exception e)
                    {
                        _SjDb.Ado.RollbackTran();
                        throw Oops.Oh($"异常：{e.Message}");
                    }
                }

            }
            else
            {
                throw Oops.Oh("状态码提交异常，驳回！");
            }

        }
    }
}

